package com.plugin.flutter.honeywell_scanner;

import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Handler;

import java.util.Map;
import android.util.Log;

import androidx.annotation.NonNull;
import io.flutter.embedding.engine.plugins.FlutterPlugin;
import io.flutter.plugin.common.BinaryMessenger;
import io.flutter.plugin.common.MethodCall;
import io.flutter.plugin.common.MethodChannel;
import io.flutter.plugin.common.MethodChannel.MethodCallHandler;
import io.flutter.plugin.common.MethodChannel.Result;
import io.flutter.plugin.common.PluginRegistry.Registrar;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;


public class HoneywellScannerPlugin implements FlutterPlugin, MethodCallHandler
{
    private static final String _INTENT_ACTION = "com.pfa.barcode";
   
    private static final String _METHOD_CHANNEL = "honeywellscanner";
    private static final String _GET_CODE = "getCode";

    private Context context;
    private MethodChannel channel;
    private BroadcastReceiver barcodeReceiver;

  @Override
  public void onAttachedToEngine(@NonNull FlutterPluginBinding flutterPluginBinding) {
    channel = new MethodChannel(flutterPluginBinding.getBinaryMessenger(), _METHOD_CHANNEL);
    context = flutterPluginBinding.getApplicationContext();
    channel.setMethodCallHandler(this::onMethodCall);
    registerBarcodeReceiver();
  }

  public void onMethodCall(MethodCall call, Result result) {
    // if (call.method.equals("getBarcode")) {
    //   // This method will be called from Flutter to start listening for barcode broadcasts
    // } else {
    //   result.notImplemented();
    // }
  }

  public void registerBarcodeReceiver() {
    barcodeReceiver = new BroadcastReceiver() {
      @Override
      public void onReceive(Context context, Intent intent) {
        if (intent.getAction().equals(_INTENT_ACTION)) {
          String data = intent.getStringExtra("data");
          channel.invokeMethod(_GET_CODE, data);
        }
      }
    };
    IntentFilter filter = new IntentFilter(_INTENT_ACTION);
    context.registerReceiver(barcodeReceiver, filter);
  }

  @Override
  public void onDetachedFromEngine(@NonNull FlutterPluginBinding binding) {
    context.unregisterReceiver(barcodeReceiver);
    channel.setMethodCallHandler(null);
  }
}
